#!/usr/local/bin/perl
use strict;
use File::Basename;
use Cwd 'abs_path';

my $S       = 'https://svl-svn.juniper.net/svn/junos-2009';
my $bindir  = abs_path(dirname($0));
my $workdir = '/d/smandal/rlog-svn-2009';
my $running = "$workdir/running.txt";
my $sqlite;

$ENV{PATH} = '/opt/CollabNet_Subversion/bin'
           . ':/sbin:/usr/sbin:/bin:/usr/local/sbin'
           . ':/usr/local/bin:/usr/bin:/volume/labtools/bin'
           . ':/volume/buildtools/bin:/volume/sw-tools/bin'
           . ':/usr/ccs/bin'
           ;
if (-e '/usr/local/bin/sqlite3') {
    $sqlite = '/usr/local/bin/sqlite3';
}
elsif (-e '/usr/bin/sqlite3') {
    $sqlite = '/usr/bin/sqlite3';
}
if (-e "$bindir/sqlite3-freebsd-captive/sqlite") {
    $sqlite = "$bindir/sqlite3-freebsd-captive/sqlite";
}

my $hostname = `hostname`;
chomp $hostname;
exit 1 if ($hostname ne 'svl-junos-pool47.juniper.net');
grab_running_lock();


chdir $workdir;

exit 1 if(!-f 'db.good');

system "$sqlite db.good 'select max(rev) from nodes' >revmax_db.txt";
my $revmax_db = `cat revmax_db.txt`;
chomp $revmax_db;
my $revmax_repo = `svn info $S|grep Revision:|sed 's/^.* //'`;
chomp $revmax_repo;
exit 0 if ($revmax_db == $revmax_repo);

system "cp db.good db";
system "perl -I$bindir $bindir/capture-rlog-pl.pl --db db";
system "perl -I$bindir $bindir/nodes.pl --db db";
system "perl -I$bindir $bindir/branches.pl --db db";
system "perl -I$bindir $bindir/merges.pl --db db";
system "$sqlite db .dump >db.sql";

my @diff = `diff db.good.sql db.sql | grep '<'`;
if ((scalar @diff == 1) || (scalar @diff == 2)) {
    system "rm db.good; mv db.sql db.good.sql";
    system "$sqlite db.good <db.good.sql";
    system "/usr/local/bin/rsync -e ssh -a db.good om\@172.22.18.160:/home/om/public_html/db";
}
else {
    print "May be something is wrong\n";
    print "@diff";
}

sub grab_running_lock
{
    exit 1 if (running());
    unlink $running;
    if (-l $running) {
        die "Error: Could not delete $running.\n";
    }
    symlink $$, $running;
    if (!-l $running) {
        die "Error: Could not create symlink $running.\n";
    }
}

sub running
{

    my $oldpid;

    return 0 if (! -l $running);
    $oldpid = readlink $running;
    if ($oldpid !~ /^\d+$/) {
        die "Error: $running does not point to a pid. It should.\n";
    }
    return 1 if (getpgrp($oldpid) != -1);  # It's an active process
    return 0;
}


